package com.gitee.dictionary.config;

import com.gitee.dictionary.base.BaseDictionaryEnum;
import com.gitee.dictionary.base.HandleDictionaryEnums;
import com.gitee.dictionary.properties.DictionaryEnumProperties;
import com.gitee.dictionary.register.DictionaryEnumTypeHandlerRegister;
import com.gitee.dictionary.base.impl.DefaultHandleDictionaryEnumsImpl;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnSingleCandidate;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author <a href="mailto:lin-mt@outlook.com">lin-mt</a>
 */
@Configuration
@EnableConfigurationProperties(DictionaryEnumProperties.class)
@ConditionalOnSingleCandidate(SqlSessionFactory.class)
@AutoConfigureAfter(MybatisAutoConfiguration.class)
public class DictionaryEnumAutoConfig<T extends BaseDictionaryEnum> {
    
    public static final String MYBATIS_DICTIONARY_ENUM_PREFIX = "dictionary-enum.mybatis";
    
    private final DictionaryEnumProperties dictionaryEnumProperties;
    
    public DictionaryEnumAutoConfig(DictionaryEnumProperties dictionaryEnumProperties) {
        this.dictionaryEnumProperties = dictionaryEnumProperties;
    }
    
    @Bean
    @ConditionalOnMissingBean(DictionaryEnumTypeHandlerRegister.class)
    public DictionaryEnumTypeHandlerRegister<T> registerDictionaryEnumTypeHandler(
            HandleDictionaryEnums<T> handleDictionaryEnums) {
        return new DictionaryEnumTypeHandlerRegister<>(this.dictionaryEnumProperties, handleDictionaryEnums);
    }
    
    @Bean
    @ConditionalOnMissingBean(HandleDictionaryEnums.class)
    public HandleDictionaryEnums<T> dictionaryEnumChecker() {
        return new DefaultHandleDictionaryEnumsImpl<>(this.dictionaryEnumProperties);
    }
}
